// 清空 user 模块

import { getToken, removeToken, setToken } from '@/utils/auth'
import { getSysProfile, login } from '@/api/user'
import { constantRoutes } from '@/router/index'
import { resetRouter } from '@/router/index'
export default {
  namespaced: true, // 开启子模块的命名空间
  state: {
    // ?? 空值合并
    // 表达式 ?? ''
    // 当左边的表达式仅为：null 或者是 undefined 的时候，才返回右边的值
    token: getToken() || '',
    // 用户数据
    userInfo: {},
    routes: constantRoutes
  },
  mutations: {
    setToken(state, token) {
      // 更新状态
      state.token = token
      // 同步缓存
      setToken(token)
    },
    removeToken(state) {
      state.token = null

      // 快捷键：ctrl + i，可以借助工具提示导入
      removeToken()
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    setRoutes(state, newRoutes) {
      state.routes = [...constantRoutes, ...newRoutes]
    }

  },
  actions: {
    async userLogin({ commit }, data) {
      try {
        const token = await login(data)
        commit('setToken', token)
      } catch (error) {
        console.log('error', error)
      }
    },
    async getUserInfo({ commit }) {
      try {
        const info = await getSysProfile()
        commit('setUserInfo', info)
        return info
      } catch (error) {
        console.log('error', error)
      }
    },
    logout({ commit }) {
      commit('removeToken')
      commit('setUserInfo', '')
      // 重置路由
      resetRouter()
    }
  }
}
